<?php
require_once dirname(__FILE__).'/../../productPage/lib/ProductPageHelper.class.php';

class categoryPageActions extends myFrontendAction{
	
	public function executeTest(){
		$this->getRoute()->getObject();
	}

	public function preExecute(){
		parent::preExecute();

		$this->category = $this->getRoute()->getCategoryObject();

		// Save current page to allow transparent navigation
		$this->getUser()->setAttribute('page',
			$this->getRequest()->getParameter('page', 1)
		);
	}

	static private $showByAr = array(10 => 10,20 =>20,50 => 50);
	static private $sortByAr = array('a-z' => 'name', 'date' => 'created_at');
									
	
	public function executeIndex( sfWebRequest $request )
    {
        /**
         * Loading helpers to use system variables
         */
        sfContext::getInstance()->getConfiguration()->loadHelpers('Variable');

        
        /**
         * Sorting context
         */
        $this->getUser()->setAttribute('sort', 'a-z');  // We need it by default
        
        if($request->getParameter('sort')) {
            if(isset(self::$sortByAr[$request->getParameter('sort')])) {
                $this->getUser()->setAttribute('sort', $request->getParameter('sort'));
            }
        }
        
		$this->pager = new sfDoctrinePager('Product', variable('per_page', 3));
		
  		$this->pager->setQuery($this->getCategoryProductsQuery());
  		$this->pager->setPage($request->getParameter('page', 1));
  		$this->pager->init();
  		
  		if($this->pager->getNbResults() >= 1) {
  			$this->page = new AttitudePagination($request->getParameter('page', 1), ceil($this->pager->getNbResults() / variable('per_page', 3)));
  		}
	}

	private function getCategoryProductsQuery()
	{
		$q = Doctrine::getTable('Product')
			->getAssociatedToCategoryProductsQuery($this->getRoute()->getCategoryObject()->getId());

		return $this->setCategoryQueryConstraints($q);
	}

	protected function setCategoryQueryConstraints( Doctrine_Query $q )
	{
		$q->innerJoin($q->getRootAlias().'.Translation t');

		Doctrine::getTable('Product')->addProductPicturesJoin( $q );

		switch($this->getUser()->getAttribute('sort')){
			case 'a-z':
				$q->orderBy('t.name asc');
				break;
			case 'date':
				$q->orderBy($q->getRootAlias() . '.created_at asc');
				break;
		}
        
		return $q;
	}
}